package controllers;

import play.*;
import play.mvc.*;
import play.data.validation.*;
import play.data.validation.Error;
import play.data.validation.Validation;
import java.util.*;
import java.io.*;
import java.lang.String;
import com.google.gson.*;
import models.*;

public class Application extends Controller {

    public static void index() {
        render();
    }
	
	public static void uploadRequest() {	
		// Response Object
		Gson gson = new Gson();
		ResponseJson respJsonObj = new ResponseJson();
		respJsonObj.API = "Upload";
		
		// Get the body of the HTTP Request - Parse the body 
		String jsonBody = request.params.get("body");
		
		// Check if request body contains a JSON object
		if (!(request.contentType).equals("application/json") || jsonBody.replace(" ","").length() == 0)
		{
			respJsonObj.response = "Error";
			respJsonObj.message = "Expecting a JSON object. No such object found";
			renderJSON(gson.toJson(respJsonObj));
		}
					
		Sensor jsonData = new Sensor();
		
		// Validation of the request parameters

		try {			
			jsonData = gson.fromJson(jsonBody, Sensor.class);
		}
		catch(JsonSyntaxException e){
			respJsonObj.response = "Error";
			respJsonObj.message = "Invalid JSON string. Please check the JSON representation for empty/incorrect values or missing separators.";
			respJsonObj.message += " <" + e.getMessage().replace("com.google.gson.stream.MalformedJsonException: ","") + ">";
			renderJSON(gson.toJson(respJsonObj));
		}
		catch(Exception e) {
			respJsonObj.response = "Error";
			respJsonObj.message = e.getMessage();
			renderJSON(gson.toJson(respJsonObj));
		}
		

		// For debugging purposes only	
		// System.out.println("--------------------------------");	
		// System.out.println("\nSensorID: " + jsonData.sensorID + " Time: "+jsonData.time+" Readings: "+ jsonData.sensorReadings);
		
        validation.valid(jsonData);
        
        if(validation.hasErrors()) {
			respJsonObj.response = "Error";
        	for(Error error : validation.errors()) 
        		respJsonObj.message +=  " " + error.message();
        	renderJSON(gson.toJson(respJsonObj));
        }
        // Update the database and send reply back to the client
		jsonData.save();
		respJsonObj.response = "Success";
		respJsonObj.message = "Uploaded Sensor data successfully";
		renderJSON(gson.toJson(respJsonObj));    	
    }
    
    
	public static void downloadRequest() {		
		// Response Object
		Gson gson = new Gson();
		ResponseJson respJsonObj = new ResponseJson();
		respJsonObj.API = "Download";		

		// Get the body of the HTTP Request
		String jsonBody = request.params.get("body");
		
		// Check if request body contains a JSON object
		if (!(request.contentType).equals("application/json") || jsonBody.replace(" ","").length() == 0)
		{
			respJsonObj.response = "Error";
			respJsonObj.message = "Expecting a JSON object. No such object found";
			renderJSON(gson.toJson(respJsonObj));
		}
		
		
		DownloadJsonClass jsonData = new DownloadJsonClass();
				
		try {			
			jsonData = gson.fromJson(jsonBody, DownloadJsonClass.class);
		}
		catch(JsonSyntaxException e){
			respJsonObj.response = "Error";
			respJsonObj.message = "Invalid JSON string. Please check the JSON representation for empty/incorrect values or missing separators.";
			respJsonObj.message += " <" + e.getMessage().replace("com.google.gson.stream.MalformedJsonException: ","") + ">";
			renderJSON(gson.toJson(respJsonObj));
		}
		catch(Exception e) {
			respJsonObj.response = "Error";
			respJsonObj.message = e.getMessage();
			renderJSON(gson.toJson(respJsonObj));
		}

		int sensorID = jsonData.sensorID;
		long startTime = jsonData.startTime;
		long endTime = jsonData.endTime;
		
		// For debugging purposes only	
		// System.out.println("------------------");			
		// System.out.println("\n SensorID: "+ sensorID + " STime: "+startTime+" EndTime: "+ endTime);
		
		
        validation.valid(jsonData);
        
         if(validation.hasErrors()) {
			respJsonObj.response = "Error";
        	for(Error error : validation.errors()) 
        		respJsonObj.message +=  " " + error.message();
        	renderJSON(gson.toJson(respJsonObj));
        }
		
		
        // Retrieve content from the MongoDB
		List<Sensor> sensors = Sensor.q().filter("sensorID", sensorID ).filter("time >= ", startTime).filter("time <= ", endTime).retrievedFields(false, "_id").asList();
		  		
		// Send back the retrieved documents (results) to the client
		if(!sensors.isEmpty())
			renderJSON(sensors);
		else {
			respJsonObj.response = "Retrieval Request Status";
			respJsonObj.message = "No documents found";
       		renderJSON(gson.toJson(respJsonObj));
       	}
    }    
}
